<template>
  <div>
    <!-- 搜索 & 新增 -->
    <!-- 搜索栏美化 -->
    <div class="search-toolbar">
      <el-input
          v-model="filters.name"
          placeholder="按用户姓名搜索"
          clearable
          @clear="onSearch"
          @keyup.enter="onSearch"
          style="width: 280px"
      >
        <template #append>
          <el-button @click="onSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>


    <!-- 列表 -->
    <el-table
        v-if="list.length"
        :data="list"
        border
        stripe
        style="width: 100%; margin-top: 8px"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="clientName" label="姓名" />
      <el-table-column prop="clientAge" label="年龄" />
      <el-table-column prop="clientType" label="护理类型" />
      <el-table-column prop="careLevelName" label="护理级别" />
      <el-table-column prop="clientLike" label="喜好" />
      <el-table-column prop="notice" label="备注" />

      <!-- 操作列：根据是否有 setId 显示不同按钮 -->
      <el-table-column label="膳食配置" width="180">
        <template #default="{ row }">
          <!-- 如果已有配置 -->
          <template v-if="row.setId">
            <el-button size="small" type="primary" @click="toEdit(row)">
              修改
            </el-button>
            <el-button size="small" type="danger" @click="onDelete(row.setId)">
              删除
            </el-button>
          </template>
          <!-- 如果未配置 -->
          <template v-else>
            <el-button
                size="small"
                type="success"
                @click="toAdd(row)"
            >
              添加膳食配置
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="订餐记录" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="goToMealRecord(row.clientId, row.clientName)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty">暂无用户</div>

    <!-- 分页 -->
    <div class="pagination" v-if="pagination.total > 0">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[5, 10, 20, 50]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>


    <!-- 新增/编辑 Dialog -->
    <el-dialog
        :title="isEditing ? '修改膳食配置' : '新增膳食配置'"
        v-model="showDialog"
        width="480px"
        @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <!-- 用户固定，不可修改 -->
        <el-form-item label="用户">
          <el-input v-model="form.clientName" disabled />
        </el-form-item>

        <el-form-item label="喜好">
          <el-input
              v-model="form.clientLike"
              type="textarea"
              :rows="3"
              placeholder="请输入客户膳食偏好"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              v-model="form.notice"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
          />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ isEditing ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

import {
  listMealSetsWithClient,
  createMealSet,
  updateMealSet,
  deleteMealSet
} from '@/api/apiList/mealSet'
import { useRouter } from 'vue-router'
const router = useRouter()

/** 列表 & 筛选 **/
const list = ref([])
const filters = reactive({ name: '' })

/** 分页 **/
const pagination = reactive({ current: 1, size: 10, total: 0 })

/** 弹窗 & 表单 **/
const showDialog = ref(false)
const isEditing = ref(false)
const form = reactive({
  setId: null,
  clientId: null,
  clientName: '',
  clientLike: '',
  notice: ''
})

/** 拉取列表 **/
async function fetchList() {
  try {
    const params = {
      name: filters.name,
      adId: localStorage.getItem('adminId'),
      role:localStorage.getItem('role'),
      page: pagination.current,
      size: pagination.size
    }
    console.log(localStorage.getItem('adminId'))
    console.log(localStorage.getItem('role'))
    const pageData = await listMealSetsWithClient(params)
    list.value = pageData.records
    pagination.total = pageData.total
  } catch {
    ElMessage.error('获取用户列表失败')
  }
}

function onSearch() {
  pagination.current = 1
  fetchList()
}
function handlePageChange(page) {
  pagination.current = page
  fetchList()
}
function handleSizeChange(size) {
  pagination.size = size
  pagination.current = 1
  fetchList()
}
async function goToMealRecord(clientId, clientName) {
  // 保存当前查看人姓名
  localStorage.setItem('currentMealViewer', clientName)

  // 跳转并传 clientId
  await router.push({ name: 'MealRecord', params: { clientId } })
}

/** 点击「添加膳食配置」 **/
function toAdd(row) {
  console.log('👉 toAdd row =', row)
  isEditing.value = false
  resetForm()
  form.clientId   = row.clientId   // 这一句如果 row.clientId 本身就是 undefined，那这里就赋不进去了
  form.clientName = row.clientName
  console.log('👉 toAdd after assign, form.clientId =', form.clientId)
  showDialog.value = true
}

/** 点击「修改」 **/
function toEdit(row) {
  isEditing.value = true
  form.setId      = row.setId
  form.clientId   = row.clientId
  form.clientName = row.clientName
  form.clientLike = row.clientLike
  form.notice     = row.notice
  showDialog.value = true
}

/** 重置表单 **/
function resetForm() {
  form.setId = null
  form.clientId = null
  form.clientName = ''
  form.clientLike = ''
  form.notice = ''
}

/** 提交创建或更新 **/
async function submitForm() {
  // 调试输出
  console.log('👉 submitForm before send:', JSON.stringify(form));

  try {
    if (isEditing.value) {
      await updateMealSet(form);
      ElMessage.success('更新成功');
    } else {
      await createMealSet(form);
      ElMessage.success('创建成功');
    }
    showDialog.value = false;
    fetchList();
  } catch (err) {
    console.error('submitForm error:', err);
    ElMessage.error((isEditing.value ? '更新' : '创建') + '失败');
  }
}

/** 删除 **/
async function onDelete(id) {
  try {
    await ElMessageBox.confirm('确认删除该膳食配置？', '提示', { type: 'warning' })
    await deleteMealSet(id)
    ElMessage.success('删除成功')
    fetchList()
  } catch {
    // 取消或失败不处理
  }
}
onMounted(fetchList)
</script>

<style scoped>
.empty {
  text-align: center;
  margin: 40px 0;
  color: #888;
}
/* 搜索框区域增强 */
.search-toolbar {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

/* 表格按钮统一 spacing */
.el-table .el-button {
  margin-right: 8px;
}

/* 表单 Dialog 样式优化 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-dialog__footer {
  text-align: right;
  padding: 10px 30px 20px;
}

.el-dialog__footer .el-button {
  min-width: 90px;
  margin-left: 12px;
}

/* 空数据提示美化 */
.empty {
  text-align: center;
  margin: 40px 0;
  color: #999;
  font-size: 15px;
}

/* 分页样式微调 */
.pagination {
  margin-top: 20px;
  text-align: right;
}

</style>
